<template>
  <div class="product-detail-modal">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-tabs v-model="activeKey">
          <!-- 基本信息 -->
          <a-tab-pane key="1" tab="基本信息">
            <a-row>
              <a-col :span="12">
                <a-form-item label="门窗系列" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入门窗系列" v-decorator="['windowSeries', validatorRules.windowSeries]" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="门窗窗号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入门窗窗号" v-decorator="['windowNo', validatorRules.windowNo]" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="门窗颜色" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入门窗颜色" v-decorator="['windowColor', validatorRules.windowColor]" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    v-decorator="['quantity', validatorRules.quantity]"
                    placeholder="请输入数量"
                    :min="1"
                    @change="calculateTotalArea"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="单窗面积(㎡)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    v-decorator="['singleWindowArea', validatorRules.singleWindowArea]"
                    placeholder="请输入单窗面积"
                    :precision="2"
                    @change="calculateTotalArea"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="总面积(㎡)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    v-decorator="['totalArea']"
                    placeholder="系统自动计算"
                    :precision="2"
                    disabled
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="成本" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number style="width: 100%" v-decorator="['cost']" placeholder="请输入成本" :precision="2" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="单窗重量(Kg/㎡)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    v-decorator="['singleWindowWeight']"
                    placeholder="请输入单窗重量"
                    :precision="2"
                    @change="calculateTotalWeight"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="12">
                <a-form-item label="总重量(Kg)" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input-number
                    style="width: 100%"
                    v-decorator="['totalWeight']"
                    placeholder="系统自动计算"
                    :precision="2"
                    disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="安装位置" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入安装位置" v-decorator="['installationLocation']" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-item label="技术要求" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <a-textarea
                    placeholder="请输入技术要求"
                    v-decorator="['technicalRequirements']"
                    :autoSize="{ minRows: 3, maxRows: 6 }"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-item label="备注" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <a-textarea
                    placeholder="请输入备注"
                    v-decorator="['remark']"
                    :autoSize="{ minRows: 3, maxRows: 6 }"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row>
              <a-col :span="24">
                <a-form-item label="图纸" :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                  <j-upload
                    v-decorator="['drawingFile']"
                    :fileMax="1"
                    :trigger-change="true"
                    accept=".jpg,.jpeg,.png,.pdf,.dwg"
                  />
                  <div class="upload-tip">支持JPG、PNG、PDF和DWG格式的图纸文件</div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>

          <!-- 玻璃尺寸表 -->
          <a-tab-pane key="2" tab="玻璃尺寸表" :forceRender="true">
            <a-table
              :columns="glassColumns"
              :dataSource="glassDataSource"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
            >
            </a-table>
          </a-tab-pane>

          <!-- 型材尺寸表 -->
          <a-tab-pane key="3" tab="型材尺寸表" :forceRender="true">
            <a-table
              :columns="profileColumns"
              :dataSource="profileDataSource"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
            ></a-table>
          </a-tab-pane>

          <!-- 配件表 -->
          <a-tab-pane key="4" tab="配件表" :forceRender="true">
            <a-table
              :columns="accessoriesColumns"
              :dataSource="accessoriesDataSource"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
            ></a-table>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-spin>

    <div class="drawer-bottom">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit" :loading="confirmLoading">确定</a-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProductDetailModal',
  props: {
    mode: {
      type: String,
      required: true,
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: this.$form.createForm(this),
      confirmLoading: false,
      activeKey: '1',

      // 表单布局
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },

      // 表单验证规则
      validatorRules: {
        windowSeries: { rules: [{ required: true, message: '请输入门窗系列!' }] },
        windowNo: { rules: [{ required: true, message: '请输入门窗窗号!' }] },
        windowColor: { rules: [{ required: true, message: '请输入门窗颜色!' }] },
        quantity: { rules: [{ required: true, message: '请输入数量!' }] },
        singleWindowArea: { rules: [{ required: true, message: '请输入单窗面积!' }] },
      },

      // 玻璃尺寸表数据
      glassDataSource: [],
      glassColumns: [
        { title: '序号', dataIndex: 'serialNo', width: 80 },
        { title: '玻璃宽', dataIndex: 'glassWidth', width: 120 },
        { title: '玻璃高', dataIndex: 'glassHeight', width: 120 },
        { title: '数量', dataIndex: 'quantity', width: 80 },
        { title: '玻璃种类', dataIndex: 'glassType', width: 150 },
      ],

      // 型材尺寸表数据
      profileDataSource: [],
      profileColumns: [
        { title: '序号', dataIndex: 'serialNo', width: 80 },
        { title: '型材代码', dataIndex: 'profileCode', width: 120 },
        { title: '型材名称', dataIndex: 'profileName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '数量', dataIndex: 'quantity', width: 80 },
        { title: '长度', dataIndex: 'length', width: 100 },
        { title: '单位', dataIndex: 'unit', width: 80 },
      ],

      // 配件表数据
      accessoriesDataSource: [],
      accessoriesColumns: [
        { title: '序号', dataIndex: 'serialNo', width: 80 },
        { title: '配件名称', dataIndex: 'accessoryName', width: 150 },
        { title: '规格', dataIndex: 'specification', width: 120 },
        { title: '数量', dataIndex: 'quantity', width: 80 },
        { title: '单位', dataIndex: 'unit', width: 80 },
        { title: '品牌', dataIndex: 'brand', width: 120 },
      ],
    }
  },
  created() {
    // 如果是编辑模式，初始化表单数据
    if (this.mode === 'edit' && this.detail) {
      this.initFormData()
    }
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      // 基本信息
      this.$nextTick(() => {
        this.form.setFieldsValue({
          windowSeries: this.detail.windowSeries,
          windowNo: this.detail.windowNo,
          windowColor: this.detail.windowColor,
          quantity: this.detail.quantity,
          cost: this.detail.cost,
          singleWindowArea: this.detail.singleWindowArea,
          totalArea: this.detail.totalArea,
          singleWindowWeight: this.detail.singleWindowWeight,
          totalWeight: this.detail.totalWeight,
          technicalRequirements: this.detail.technicalRequirements,
          installationLocation: this.detail.installationLocation,
          remark: this.detail.remark,
          drawingFile: this.detail.drawingFile,
        })
      })

      // 玻璃尺寸表
      if (this.detail.glassSizeTableJson) {
        try {
          this.glassDataSource = JSON.parse(this.detail.glassSizeTableJson)
        } catch (e) {
          console.error('解析玻璃尺寸表数据失败:', e)
        }
      }

      // 型材尺寸表
      if (this.detail.profileSizeTableJson) {
        try {
          this.profileDataSource = JSON.parse(this.detail.profileSizeTableJson)
        } catch (e) {
          console.error('解析型材尺寸表数据失败:', e)
        }
      }

      // 配件表
      if (this.detail.accessoriesTableJson) {
        try {
          this.accessoriesDataSource = JSON.parse(this.detail.accessoriesTableJson)
        } catch (e) {
          console.error('解析配件表数据失败:', e)
        }
      }
    },

    // 计算总面积
    calculateTotalArea() {
      const quantity = this.form.getFieldValue('quantity') || 0
      const singleWindowArea = this.form.getFieldValue('singleWindowArea') || 0

      const totalArea = quantity * singleWindowArea
      this.form.setFieldsValue({ totalArea })
    },

    // 计算总重量
    calculateTotalWeight() {
      const quantity = this.form.getFieldValue('quantity') || 0
      const singleWindowWeight = this.form.getFieldValue('singleWindowWeight') || 0
      const singleWindowArea = this.form.getFieldValue('singleWindowArea') || 0

      const totalWeight = quantity * singleWindowWeight * singleWindowArea
      this.form.setFieldsValue({ totalWeight })
    },

    // 提交表单
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true

          // 处理JSON数据
          values.glassSizeTableJson = JSON.stringify(this.glassDataSource)
          values.profileSizeTableJson = JSON.stringify(this.profileDataSource)
          values.accessoriesTableJson = JSON.stringify(this.accessoriesDataSource)

          // 合并原有数据
          const result = { ...this.detail, ...values }

          // 提交数据
          this.$emit('submit', result)
          this.confirmLoading = false
        }
      })
    },

    // 取消
    handleCancel() {
      this.$emit('cancel')
    },
  },
}
</script>

<style lang="less" scoped>
.product-detail-modal {
  position: relative;
  padding-bottom: 55px;
  height: 100%;

  .drawer-bottom {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;

    button + button {
      margin-left: 8px;
    }
  }
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}
</style> 